<?php
namespace PsiFramework\Classes\Util\Object;

import("Classes.Model.ModelInterface.IPrimitiveObject");
import("Classes.Util.Database.Query.SqlType");

use \PsiFramework\Classes\Util\Database\Query\SqlType;
use \PsiFramework\Classes\Model\ModelInterface\IPrimitiveObject;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * The Date class is used to Manage Dates
 *
 * @package Util.Object
 */
class Json implements IPrimitiveObject
{

    protected /*object*/ $_jsonObject ;
    protected /*string*/ $_jsonString ;

    /**
     * Constructor
     *
     * @param object    $jsonObject        the jsonObject
     */
    public function __construct(/*object*/ $jsonObject=null)
    {
        if (is_null($jsonObject)) {
            $jsonObject = new \stdClass();
        }
        $this->_jsonObject = $jsonObject ;
        $this->_jsonString = null ;
    }

    public function buildFromText(/*string*/ $jsonText)
    {
        $this->_jsonString = $jsonText ;
        $this->_jsonObject = json_decode($jsonText);
    }

    public function toString()
    {
        return '' ;
    }

    public function toJsonString()
    {
        $this->_jsonString = json_encode($this->_jsonObject);
        return $this->_jsonString ;
    }

    public function getObject()
    {
        return $this->_jsonObject ;
    }

    public function setObject($jsonObject)
    {
        $this->_jsonObject = $jsonObject ;
    }

    public function serialize(/*boolean*/ $asText=true)
    {
        if ($asText) {
            return  $this->toJsonString();
        } else {
            return $this->_jsonObject ;
        }
    }

    public function unserialize($value)
    {
        if (is_object($value) || is_array($value)) {
            $this->_jsonObject = $value ;
        } else if (is_string($value)) {
            $this->buildFromText($value);
        } else {
            throw new \Exception("Invalid value type : '".$value."' !");
        }
    }

    public static function getSqlType()
    {
        return SqlType::$text ;
    }
}
